//
//  ZJPictureBrowserCell.swift
//  PictureBrowser
//
//  Created by zhengju on 2017/7/27.
//  Copyright © 2017年 zhengju. All rights reserved.
//

import UIKit
import Kingfisher
public protocol ZJPictureBrowserCellDelegate : NSObjectProtocol{


    func singleTapAction(index:Int)
}
class ZJPictureBrowserCell: UICollectionViewCell,UIScrollViewDelegate {
    
    
    var scrollView: UIScrollView?
    var index: Int?
    private var touchX: CGFloat = 0.0 // 双击点的X坐标
    private var touchY: CGFloat = 0.0 // 双击点的Y坐标
   
    var imageWidth: CGFloat?
    var imageHeight: CGFloat?
    
    
    
    var imageView: UIImageView!

    weak var  delegate: ZJPictureBrowserCellDelegate?
    
    
    var imageStr: String? {
        
        didSet {
            self.imageView!.image = UIImage(named: self.imageStr! )
        }
        
    }
    var imageUrlStr: String? {
        
        didSet {
            
            self.imageView.kf.setImage(with: URL.init(string: imageUrlStr! ), placeholder: UIImage.init(named: ""), options: nil, progressBlock: { (cuInt, allInt) in
                
            }, completionHandler: { (image, error, cache, url) in
                
                self.imageWidth = self.bounds.size.width
                
                self.imageHeight = (image?.size.height)! / (image?.size.width)! * self.imageWidth!

                //设置imageView同iamge大小一致
                self.imageView.frame = CGRect.init(x: 10, y: 0, width: self.imageWidth! - 20, height: self.imageHeight!)

                self.imageView.center = (self.scrollView?.center)!
                
            })
        }
        
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView = UIScrollView(frame:self.bounds)
        scrollView?.contentSize = self.bounds.size
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.maximumZoomScale = 3
        scrollView?.minimumZoomScale = 1
        scrollView?.delegate = self
        self.addSubview(scrollView!)
        

        imageView = UIImageView(frame:CGRect.init(x: 10, y: 0, width: (scrollView?.bounds.size.width)! - 20, height: (scrollView?.bounds.size.height)!))
        
        
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
     
        scrollView?.addSubview(imageView)
        // 添加手势
        // 1.单击手势
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapClick(tap:)))
        singleTap.numberOfTapsRequired = 1
        imageView?.addGestureRecognizer(singleTap)
        // 2.双击手势
        let doubleTapGesture = UITapGestureRecognizer()
        doubleTapGesture.addTarget(self, action: #selector(handleDoubleTap(gestureRecognizer:)))
        doubleTapGesture.numberOfTapsRequired = 2
        imageView?.addGestureRecognizer(doubleTapGesture)
        
        //scrollView双击手势
        let scrollViewDoubleTap = UITapGestureRecognizer()
        scrollViewDoubleTap.addTarget(self, action: #selector(handleDoubleTap(gestureRecognizer:)))
        scrollViewDoubleTap.numberOfTapsRequired = 2
        scrollView?.addGestureRecognizer(scrollViewDoubleTap)
        
        
        // 必须加上这句，否则双击手势不管用
        singleTap.require(toFail: doubleTapGesture)

    }
    
    //MARK:保存图片到相册
    func downloadAction()  {
        UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    //MARK:复原
    func restore()  {
        
       // isScaleBig = true
        // 放大缩小

       // scrollView?.setZoomScale(1.0, animated: true)

    }

    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject)  {
        if error != nil {

            print("保存失败")
            
        } else {

            print("保存成功")
        }
    }

      // 单击手势事件
    func singleTapClick(tap: UITapGestureRecognizer) {
   
        if delegate != nil{

            delegate?.singleTapAction(index: index!)
        }
    }
    // MARK: - 双击缩放
    var isScaleBig:Bool = true
    func handleDoubleTap(gestureRecognizer:UITapGestureRecognizer)
    {

        
        if gestureRecognizer.view is UIScrollView{
       
            print("scrollView被点击...")
        
        }else{

       
            self.touchX = gestureRecognizer.location(in: gestureRecognizer.view).x
       
            self.touchY = gestureRecognizer.location(in: gestureRecognizer.view).y

            print("touchx:\(self.touchX) touchy:\(self.touchY)")

            // 放大缩小
       
            let scale = scrollView?.zoomScale
       
            if isScaleBig
       
            {
           
            
                //放大作用,三倍
                scrollView?.setZoomScale((scale! / 0.3), animated: true)

                
                
               // scrollView?.contentSize = CGSize.init(width: imageWidth! * 3, height: imageHeight! * 3)

                isScaleBig = false
       
            }
       
            else
        
            {
           
                scrollView?.setZoomScale(1, animated: true)
          
                //scrollView?.contentSize = CGSize.init(width: self.bounds.size.width, height: self.bounds.size.height)
                
                isScaleBig = true
       
            }
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        for imageView in scrollView.subviews{
            if imageView is UIImageView {
                return imageView
            }
        }
        return nil
    }
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        
        //居中显示
        let imageView = scrollView.subviews.first as! UIImageView
        centerShow(scrollview: scrollView, imageview: imageView)
    }
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat)
    {
        print(" scrollViewDidEndZooming")

    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let contentOffset = scrollView.contentOffset

        print("contentOffsetX:\(contentOffset.x)")

        print("contentOffsetY:\(contentOffset.y)")
        if isScaleBig
            
        {
            
        }
            
        else
            
        {
           
        }
    }
    func centerShow(scrollview:UIScrollView, imageview:UIImageView)
    {
   // 居中显示
        let offsetX = (scrollview.bounds.size.width > scrollview.contentSize.width) ? (scrollview.bounds.size.width - scrollview.contentSize.width) * 0.5   : 0.0 ;
        
        let offsetY = (scrollview.bounds.size.height > scrollview.contentSize.height) ?
            (scrollview.bounds.size.height - scrollview.contentSize.height) * 0.5 : 0.0;
        
        imageview.center = CGPoint(x:scrollview.contentSize.width * 0.5 + offsetX,y:scrollview.contentSize.height * 0.5 + offsetY);
        
        if  isScaleBig  {

            let contentOffset = self.scrollView?.contentOffset
            
            let center = self.scrollView?.center
            
            let offsetXX = (center?.x)! - self.touchX
            
            
            let offsetYY = (center?.y)! - (self.touchY + (self.bounds.size.height - imageHeight!)/2.0 )

            
            self.scrollView?.contentOffset = CGPoint.init(x: (contentOffset?.x)! - offsetXX * 2 , y: (contentOffset?.y)! - offsetYY * 2)

            }

    }
  
}
